package com.zhkj.txg.module.mine.ui

import android.Manifest
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tbruyelle.rxpermissions2.RxPermissions
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.lib.utils.SpanUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.cart.adapter.CartHotAdapter
import com.zhkj.txg.module.home.ui.WelfareActivity
import com.zhkj.txg.module.member.ui.MemberShareActivity
import com.zhkj.txg.module.mine.adapter.MineCateAdapter
import com.zhkj.txg.module.mine.adapter.MineOrderAdapter
import com.zhkj.txg.module.mine.adapter.MineServiceAdapter
import com.zhkj.txg.module.mine.entity.CateType
import com.zhkj.txg.module.mine.entity.MineCateEntity
import com.zhkj.txg.module.mine.entity.MineOperationEntity
import com.zhkj.txg.module.mine.entity.OperationType
import com.zhkj.txg.module.mine.popup.InvitePopupWindow
import com.zhkj.txg.module.mine.vm.MineViewModel
import com.zhkj.txg.module.order.ui.AddressManagerActivity
import com.zhkj.txg.module.order.ui.OrderListActivity
import com.zhkj.txg.module.order.ui.Type
import com.zhkj.txg.module.order.ui.group.GroupOrderListActivity
import com.zhkj.txg.module.product.ui.ProductDetailActivity
import com.zhkj.txg.utils.ConfigManager
import com.zhkj.txg.utils.GridItemDecoration
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.QRCodeUtils
import kotlinx.android.synthetic.main.activity_setting.*
import kotlinx.android.synthetic.main.fragment_collection.*
import kotlinx.android.synthetic.main.fragment_mine.*
import kotlinx.android.synthetic.main.item_mine_top.*
import kotlin.math.abs

class MineFragment : ViewModelFragment<MineViewModel>() {
    override fun setViewModel(): MineViewModel = createViewModel(false)
    override val layoutResId: Int = R.layout.fragment_mine

    private var maxScrollHeight: Int = 0
    private var refresh = false
    private var refreshAll = false

//    private var ivMineHeader: ImageView? = null
//    private var tvMineName: TextView? = null
//    private var tvMineBalance: TextView? = null
//    private var tvMineBadgeNotPay: TextView? = null
//    private var tvMineBadgeNotDelivery: TextView? = null
//    private var tvMineBadgeNotReceive: TextView? = null

    private val cateAdapter = MineCateAdapter().apply {
        setOnItemChildClickListener { _, view, position ->
            if (view.id == R.id.tvTitle) when (data[position].type) {
                // 我的收藏
                CateType.COLLECTION -> startActivity(Intent(requireContext(), CollectionActivity::class.java))
                // 我的优惠券
                CateType.COUPON -> CouponActivity.all(requireActivity())
                // 收货地址
                CateType.ADDRESS -> AddressManagerActivity.open(requireActivity())
                // 拼团订单
                CateType.GROUP -> GroupOrderListActivity.open(requireActivity(), 0)
                // 联系客服
//                CateType.CUSTOMER -> VP53Manager.getInstance().EnterChatActivity(KF_53_ARG, "1", requireContext(), null)
                // 我的足迹
                CateType.HISTORY -> startActivity(Intent(requireContext(), VisitLogActivity::class.java))
                // 我的发布
                CateType.PUBLISH -> startActivity(Intent(requireContext(), PublishListActivity::class.java))
                // 邀请好友
                CateType.INVITE -> viewModel.userLiveData.value?.response?.data?.shareUrl?.let {
                    MemberShareActivity.open(requireActivity(), it)
                }
                // 系统设置
                CateType.SETTING -> startActivity(Intent(requireContext(), SettingActivity::class.java))
                //我的邀请人
                CateType.MEMBER_INVITE -> {
                    viewModel.getReferrer()
                }
            }
        }
    }

    private val orderAdapter = MineOrderAdapter().apply {
        setOnItemClickListener { adapter, view, position ->
            val index = when (data[position].type) {
                OperationType.UNPAID -> 1//未付款
                OperationType.DELIVERED -> 2 //待发货
                OperationType.RECEIVED -> 3 //待收货
                OperationType.COMPLETED -> 4 //已完成
                OperationType.SALE -> 5 //售后
                else -> return@setOnItemClickListener
            }
            if (index == 5) {
                startActivity(Intent(requireContext(), AfterSaleActivity::class.java))
            } else {
                OrderListActivity.open(requireActivity(), index)
            }
        }
    }

    private val serviceAdapter = MineServiceAdapter().apply {
        setOnItemClickListener { adapter, view, position ->
            when (data[position].type) {
                OperationType.COLLECTION -> {
                    startActivity(Intent(requireContext(), CollectionActivity::class.java))
                } //我的收藏
                OperationType.ADDRESS -> {
                    AddressManagerActivity.open(requireActivity())
                } //收货地址
                OperationType.FOOTPRINT -> {
//                    startActivity(Intent(requireContext(), VisitLogActivity::class.java))
                    ProblemActivity.open(requireActivity())
                } //常见问题
                OperationType.CUSTOMER -> {
                    FeedbackActivity.open(requireActivity())
                } //问题反馈
                OperationType.WE -> {
                    WelfareActivity.aboutUs(requireActivity(), "关于我们")
                } //关于我们
                else -> return@setOnItemClickListener
            }
        }
    }

    private val invitePopupWindow: InvitePopupWindow by lazy {
        InvitePopupWindow(requireContext()) {
            viewModel.bindInvite(AccountManager.getToken(), it)
        }
    }

    override fun initUI() {
        with(titleMine) {
            setFragmentStatusBar()
            setRightClickListener(View.OnClickListener {
                startActivity(Intent(requireContext(), SettingActivity::class.java))
            })
        }
        maxScrollHeight = ScreenUtil.getScreenWidth(requireContext())

        with(rvMineOrder) {
            layoutManager = GridLayoutManager(context, 4).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
            }
            adapter = orderAdapter
        }

        with(rvMineService) {
            layoutManager = GridLayoutManager(context, 5).apply {
                spanSizeLookup.isSpanIndexCacheEnabled = true
            }
            adapter = serviceAdapter
        }

        // 用户资料编辑
        ivMineHeader.setOnClickListener {
            viewModel.userInfo?.let {
                EditUserInfoActivity.start(requireActivity())
            }
        }
        tvMineName?.setOnClickListener {
            ivMineHeader?.performClick()
        }
        //优惠券
        llCoupon.setOnClickListener {
            CouponActivity.all(requireActivity())
        }
        //跳转用户充值中心
        llMineLinearLayout.setOnClickListener {
//            MineBalanceActivity.start(requireActivity())
            BalanceOperationActivity.startRecharge(requireActivity())
        }

        tvMineOpenDiamond.setOnClickListener {
//            MineBalanceActivity.start(requireActivity())
            DiamondActivity.open(requireActivity())
        }
        //全部订单
        tvMineOrderAdd.setOnClickListener {
            OrderListActivity.open(requireActivity(), 0)
        }
        //二维码点击
        llMineQr.setOnClickListener {

            viewModel.userInfo?.let {
                layDialog(
                    null,
                    QRCodeUtils.createQRCodeBitmap(it.mobile, 700, 700)
                )
            }
        }
        refreshMine.setOnRefreshListener { initData() }
    }

    override fun initData() {

//        viewModel.couponList(true)

        viewModel.userCenter(AccountManager.getToken(), true).takeIf {
            !it.hasObservers()
        }?.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) {
                val data = response.response?.data
                    ?: return@Observer
                val orderList = mutableListOf(
                    MineOperationEntity("待付款", R.drawable.ic_mine_order_unpaid, OperationType.UNPAID, data.waitPayCount),
                    MineOperationEntity("待发货", R.drawable.ic_mine_order_delivered, OperationType.DELIVERED, data.waitSendCount),
                    MineOperationEntity("待收货", R.drawable.ic_mine_order_received, OperationType.RECEIVED, data.waitReceiveCount),
                    MineOperationEntity("已完成", R.drawable.ic_mine_order_completed, OperationType.COMPLETED)
//                    MineOperationEntity("售后", R.drawable.ic_mine_order_sale, OperationType.SALE)
                )
                val serviceList = mutableListOf(
                    MineOperationEntity("我的收藏", R.drawable.ic_mine_service_collection, OperationType.COLLECTION),
                    MineOperationEntity("收货地址", R.drawable.ic_mine_service_address, OperationType.ADDRESS),
                    MineOperationEntity("常见问题", R.drawable.changjianwenti, OperationType.FOOTPRINT),
                    MineOperationEntity("问题反馈", R.drawable.wentifankui, OperationType.CUSTOMER),
                    MineOperationEntity("关于我们", R.drawable.ic_mine_service_we, OperationType.WE)
                )
                data.userInfo?.let { userInfo ->
                    viewModel.userInfo = userInfo
                    ImageUtils.loadCircleImage(this@MineFragment, ivMineHeader, userInfo.avatar)
                    tvMineName?.text = userInfo.nickname
                    tvMineBalance?.text = SpanUtil.setMoneySymbol(userInfo.money)
                    orderAdapter.setNewData(orderList)
                    serviceAdapter.setNewData(serviceList)
                    refreshMine.finishRefresh()
                }
                tvCouponCount.text = data.couponCount
            } else if (response.status == HttpResponseStatus.Status.FAILURE) {
                refreshMine.finishRefresh(false)
            }
        })


//        val cateList = mutableListOf(
//            MineCateEntity(getString(R.string.my_collection), R.drawable.ic_mine_collection, CateType.COLLECTION),
//            MineCateEntity(getString(R.string.my_coupon), R.drawable.ic_mine_coupon, CateType.COUPON),
//            MineCateEntity(getString(R.string.group_list), R.drawable.ic_mine_group, CateType.GROUP),
//            MineCateEntity(getString(R.string.my_address), R.drawable.ic_mine_address, CateType.ADDRESS),
//            MineCateEntity(getString(R.string.my_customer_service), R.drawable.ic_mine_customer, CateType.CUSTOMER),
//            MineCateEntity(getString(R.string.my_History), R.drawable.ic_mine_history, CateType.HISTORY),
//            MineCateEntity(getString(R.string.my_publish), R.drawable.ic_mine_publish, CateType.PUBLISH),
//            MineCateEntity(getString(R.string.my_invite), R.drawable.ic_mine_invite, CateType.INVITE),
//            MineCateEntity(getString(R.string.member_invite), R.drawable.ic_member_inviter, CateType.MEMBER_INVITE)
////            MineCateEntity(getString(R.string.my_setting), R.drawable.ic_mine_setting, CateType.SETTING)
//        )
//        viewModel.userCenter(AccountManager.getToken(), true).takeIf {
//            !it.hasObservers()
//        }?.observe(viewLifecycleOwner, Observer { response ->
//            handlerResponseStatus(response.status, response.statusTip)
//            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.userInfo?.let { userInfo ->
//                viewModel.userInfo = userInfo
//                ImageUtils.loadCircleImage(this@MineFragment, ivMineHeader!!, userInfo.avatar)
//                tvMineName?.text = userInfo.nickname
//                tvMineBalance?.text = SpanUtil.setMoneySymbol(userInfo.money)
//                if (response.response?.data?.isMember != true) cateAdapter.replaceData(
//                    cateList.filterNot { it.type == CateType.PUBLISH || it.type == CateType.INVITE }
//                ) else cateAdapter.setNewData(cateList)
//                // 设置角标
//                val waitPayCount = response.response?.data?.waitPayCount
//                tvMineBadgeNotPay?.visibility =
//                    if (waitPayCount != null && waitPayCount > 0) View.VISIBLE else View.GONE
//                tvMineBadgeNotPay?.text = returnUICount(waitPayCount ?: 0)
//                val waitSendCount = response.response?.data?.waitSendCount
//                tvMineBadgeNotDelivery?.visibility =
//                    if (waitSendCount != null && waitSendCount > 0) View.VISIBLE else View.GONE
//                tvMineBadgeNotDelivery?.text = returnUICount(waitSendCount ?: 0)
//                val waitReceiveCount = response.response?.data?.waitReceiveCount
//                tvMineBadgeNotReceive?.visibility =
//                    if (waitReceiveCount != null && waitReceiveCount > 0) View.VISIBLE else View.GONE
//                tvMineBadgeNotReceive?.text = returnUICount(waitReceiveCount ?: 0)
//            } else if (response.status == HttpResponseStatus.Status.FAILURE) refreshMine.finishRefresh(false)
//        })
    }

    override fun onHiddenChanged(hidden: Boolean) {
        if (!hidden && refreshAll) {
            viewModel.userCenter(AccountManager.getToken(), true)
            refresh = false
            refreshAll = false
            return
        }
        if (!hidden && refresh) {
            viewModel.userCenter(AccountManager.getToken())
            refresh = false
        }
    }

    override fun onResume() {
        super.onResume()
        if (refreshAll) {
            viewModel.userCenter(AccountManager.getToken(), true)
            refresh = false
            refreshAll = false
            return
        }
        if (refresh) {
            viewModel.userCenter(AccountManager.getToken())
            refresh = false
        }
    }

    override fun initViewModel() {
        // 热门商品数据观察者
//        viewModel.hotGoodsLiveData.observe(viewLifecycleOwner, Observer { data ->
//            when (data.status) {
//                HttpResponseStatus.Status.START -> Unit
//                HttpResponseStatus.Status.SUCCESS -> data.response?.let {
//                    // 恢复加载状态
//                    if (!it.loadMore) refreshMine.finishRefresh()
//                    else if (it.hasMore) productAdapter.loadMoreModule?.loadMoreComplete()
//                    else productAdapter.loadMoreModule?.loadMoreEnd()
//                    // 填充数据
//                    if (it.loadMore) productAdapter.addData(it.data)
//                    else productAdapter.setNewData(it.data)
//                }
//                HttpResponseStatus.Status.FAILURE -> {
//                    data.exception?.printStackTrace()
//                    toast(data.statusTip)
//                    if (viewModel.page > 1) productAdapter.loadMoreModule?.loadMoreFail()
//                    else refreshMine.finishRefresh(false)
//                }
//            }
//        })
        // 余额变动数据观察者
        viewModel.balanceChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 切换账号数据观察者
        viewModel.accountChangeSubscribe().observe(viewLifecycleOwner, Observer { refreshAll = true })
        // 用户资料编辑观察者
        viewModel.userInfoChangeSubscribe().observe(viewLifecycleOwner, Observer { refresh = true })
        // 会员资格变动观察者
        viewModel.memberStatusChangeSubscribe().observe(viewLifecycleOwner, Observer { refreshAll = true })
        viewModel.orderListStatusSubscribe().observe(viewLifecycleOwner, Observer { event ->
            if (event.refreshType.any { it == Type.PAY || it == Type.SEND || it == Type.RECEIVE }) refresh = true
        })
        viewModel.referrerLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.data?.let {
                if (it.exist_parent == true && it.parent_info != null)
                    ReferrerActivity.start(requireActivity(), it.parent_info)
                else invitePopupWindow.showPopupWindow()
            }
        })
        viewModel.bindInviteLiveData.observe(viewLifecycleOwner, Observer {
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS) {
                invitePopupWindow.dismiss()
                toast("绑定成功!")
                viewModel.getReferrer()
            }
        })


        viewModel.couponListLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                HttpResponseStatus.Status.START -> Unit
                HttpResponseStatus.Status.SUCCESS -> response.response?.let {
                    tvCouponCount.text = it.data.size.toString()
                    Log.e("TAG", "=====${it.data.size}")
                }
                HttpResponseStatus.Status.FAILURE -> {
                    response.exception?.printStackTrace()
                    toast(response.statusTip)
                }
            }
        })
    }

//    private fun createHeaderView(): View = layoutInflater.inflate(R.layout.item_mine_top, null).apply {
//        ivMineHeader = findViewById(R.id.ivMineHeader)
//        tvMineName = findViewById(R.id.tvMineName)
//        tvMineBalance = findViewById(R.id.tvMineBalance)
//        tvMineBadgeNotPay = findViewById(R.id.tvMineBadgeNotPay)
//        tvMineBadgeNotDelivery = findViewById(R.id.tvMineBadgeNotDelivery)
//        tvMineBadgeNotReceive = findViewById(R.id.tvMineBadgeNotReceive)
//
//        with(findViewById<RecyclerView>(R.id.rvMineTab)) {
//            layoutManager = GridLayoutManager(context, 4)
//            adapter = cateAdapter
//            hasFixedSize()
//        }
//        // 订单列表页点击事件监听
//        findViewById<View>(R.id.tvMineAllOrder).setOnClickListener {
//            OrderListActivity.open(requireActivity(), 0)
//        }
//        findViewById<View>(R.id.tvMineOrderNonPayment).setOnClickListener {
//            OrderListActivity.open(requireActivity(), 1)
//        }
//        findViewById<View>(R.id.tvMineOrderNonDelivery).setOnClickListener {
//            OrderListActivity.open(requireActivity(), 2)
//        }
//        findViewById<View>(R.id.tvMineOrderNonReceive).setOnClickListener {
//            OrderListActivity.open(requireActivity(), 3)
//        }
//        findViewById<View>(R.id.tvMineOrderComplete).setOnClickListener {
//            OrderListActivity.open(requireActivity(), 4)
//        }
//        // 跳转售后列表页
//        findViewById<View>(R.id.tvMineOrderAfterSale).setOnClickListener {
//            startActivity(Intent(requireContext(), AfterSaleActivity::class.java))
//        }
//        // 用户资料编辑
//        findViewById<View>(R.id.ivMineHeader).setOnClickListener {
//            viewModel.userInfo?.let {
//                EditUserInfoActivity.start(requireActivity())
//            }
//        }
//        findViewById<View>(R.id.tvMineBalance).setOnClickListener {
//            MineBalanceActivity.start(requireActivity())
//        }
//        tvMineName?.setOnClickListener { ivMineHeader?.performClick() }
//    }

    private fun returnUICount(realCount: Int) = when (realCount) {
        in 0..99 -> realCount.toString()
        else -> "99"
    }


    /**
     * 自定义布局的对话框
     */
    private fun layDialog(title: String?, content: Bitmap?) {
        val view: View = LayoutInflater.from(requireContext()).inflate(
            R.layout.dialog_coupon_qr, null, false
        )
        val dialog = Dialog(requireContext())
        dialog.setContentView(view)
        dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent)
        val tvCouponCode: TextView = view.findViewById(R.id.tvCouponCode)
        val ivCouponQR: ImageView = view.findViewById(R.id.ivCouponQR)
        if (title == null) {
            tvCouponCode.visibility = View.GONE
        } else {
            tvCouponCode.text = title
        }
        if (content == null) {
            ivCouponQR.visibility = View.GONE
            toast("二维码生成错误")
        } else {
            ivCouponQR.visibility = View.VISIBLE
            ivCouponQR.setImageBitmap(content)
        }
        dialog.show()
    }
}